<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Carbon;
use JetBrains\PhpStorm\ArrayShape;

/**
 * App\Models\UserCoupon
 *
 * @property int $id
 * @property int $user_id 用户ID
 * @property int $coupon_id 优惠券ID
 * @property int $mode 类型:0=洗车优惠券,1=商品优惠券
 * @property string $title 优惠券标题
 * @property int $range 使用限制:0=全场通用,1=指定分类,2=指定服务
 * @property string $full_price 满足使用条件
 * @property string $price 优惠金额
 * @property int $shop_id 门店ID
 * @property int $cid 分类ID
 * @property int $good_id 商品ID
 * @property int $service_id 服务ID
 * @property mixed|null $areas 所属地区ID组,默认null表示全国地区显示
 * @property string $start_time 开启日期
 * @property string $end_time 结束日期
 * @property int $status 状态:0=未使用,1=已使用
 * @property string|null $used_time 使用时间
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property-read \App\Models\User|null $user
 * @method static Builder|UserCoupon newModelQuery()
 * @method static Builder|UserCoupon newQuery()
 * @method static Builder|UserCoupon query()
 * @method static Builder|UserCoupon whereAreas($value)
 * @method static Builder|UserCoupon whereCid($value)
 * @method static Builder|UserCoupon whereCouponId($value)
 * @method static Builder|UserCoupon whereCreatedAt($value)
 * @method static Builder|UserCoupon whereEndTime($value)
 * @method static Builder|UserCoupon whereFullPrice($value)
 * @method static Builder|UserCoupon whereGoodId($value)
 * @method static Builder|UserCoupon whereId($value)
 * @method static Builder|UserCoupon whereMode($value)
 * @method static Builder|UserCoupon wherePrice($value)
 * @method static Builder|UserCoupon whereRange($value)
 * @method static Builder|UserCoupon whereServiceId($value)
 * @method static Builder|UserCoupon whereShopId($value)
 * @method static Builder|UserCoupon whereStartTime($value)
 * @method static Builder|UserCoupon whereStatus($value)
 * @method static Builder|UserCoupon whereTitle($value)
 * @method static Builder|UserCoupon whereUpdatedAt($value)
 * @method static Builder|UserCoupon whereUsedTime($value)
 * @method static Builder|UserCoupon whereUserId($value)
 * @mixin \Eloquent
 */
class UserCoupon extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'user_coupons';

    protected $fillable = [
        "user_id","coupon_id","mode","title","range","full_price","price","shop_id",
        "cid","service_id","price","areas","status","start_time","end_time"
    ];

    protected $casts = ['full_price'=>'float','price'=>'float'];

    /**
     * 添加优惠券
     * @param $id
     * @param $user_id
     */
    public static function addCoupon($id,$user_id)
    {
        $coupon = Coupon::find($id);
        if (!$coupon){
            modelError("找不到此优惠券!");
        }
        $exit = self::query()->where("coupon_id",$id)->where("user_id",$user_id)->exists();
        if ($exit){
            modelError("此优惠券已领取,不可重复领取!");
        }
        $params = [
            'user_id'=>$user_id,"coupon_id"=>$id,'mode'=>$coupon->mode,
            'title'=>$coupon->title,'range'=>$coupon->range,
            'full_price'=>$coupon->full_price,'price'=>$coupon->price,
            'cid'=>$coupon->cid,'service_id'=>$coupon->service_id,
            'areas'=>$coupon->areas,'status'=>0,"shop_id"=>$coupon->shop_id
        ];
        $days = $coupon->days;
        $start_time = now()->format("Y-m-d");
        $end_time = Carbon::parse($start_time)->addDays($days)->format("Y-m-d");
        $params['start_time'] = $start_time;
        $params['end_time'] = $end_time;
        return self::create($params);
    }

    public function user(): HasOne
    {
        return $this->hasOne(User::class,"id","user_id");
    }

    /**
     * 获取优惠券列表
     * @param $user_id
     * @return array
     */
    public static function getList($user_id): array
    {
        $pageSize = request()->input("pageSize",10);
        $where = ['status'=>0,'mode'=>0,'user_id'=>$user_id];
        $model = self::query()->where($where);
        $type = request()->input("type",0);
        if ($type){
            $query = $model->whereDate("start_time",">",now())
                ->whereDate("end_time","<",now());
        }else{
            $query = $model->whereDate("start_time","<=",now())
                ->whereDate("end_time",">=",now());
        }
        $list = $query->orderByDesc("id")->paginate($pageSize);
        foreach ($list as $item){
            $shop = ShopUser::query()->where("id",$item->shop_id)->first();
            $item->text = $shop?"仅限【{$shop->name}】使用":"";
        }
        $data['items'] = $list->items();
        $data['lastPage'] = $list->lastPage();
        $data['total'] = $list->total();
        return $data;
    }

    /**
     * @param $user_id
     * @return array
     */
    public static function allows($user_id): array
    {
        $service_id = request()->input("service_id","");
        $price = request()->input("price","");
        $status = request()->input("status",0);
        $service = Service::find($service_id);
        if (!$service){
            modelError("找不到此服务!");
        }
        $cid = $service->cid;
        $shop_id = $service->shop_id;
        $map1 = ['status'=>0,'mode'=>0,"range"=>0,'user_id'=>$user_id,"shop_id"=>$shop_id];
        $map2 = ['status'=>0,'mode'=>0,"range"=>1,'user_id'=>$user_id,"shop_id"=>$shop_id,"cid"=>$cid];
        $map3 = ['status'=>0,'mode'=>0,"range"=>2,'user_id'=>$user_id,"shop_id"=>$shop_id,"service_id"=>$service_id];
        if ($status){
            $where1 = function ($query) use ($map1,$price) {
                $query->where($map1)->where("full_price",">",$price);
            };
            $where2 = function ($query) use ($map2,$price) {
                $query->where($map2)->where("full_price",">",$price);
            };
            $where3 = function ($query) use ($map3,$price) {
                $query->where($map3)->where("full_price",">",$price);
            };
            $list = self::query()
                ->where($where1)
                ->orWhere($where2)
                ->orWhere($where3)
                ->orWhere("shop_id","<>",$shop_id)
                ->get();
        }else{
            $where1 = function ($query) use ($map1,$price) {
                $query->where($map1)->where("full_price","<=",$price);
            };
            $where2 = function ($query) use ($map2,$price) {
                $query->where($map2)->where("full_price","<=",$price);
            };
            $where3 = function ($query) use ($map3,$price) {
                $query->where($map3)->where("full_price","<=",$price);
            };
            $list = self::query()
                ->where($where1)
                ->orWhere($where2)
                ->orWhere($where3)
                ->get();
        }
        return $list->toArray();
    }
}
